import { GetAdminList } from "@/api/funcList";
import i18n from "@/lang";
import { useAdminStore } from '@/stores/adminStore';
import { ref } from 'vue';

const { t } = i18n.global;

// 定义功能列表枚举类型（与后端FuncListTypeEnum对应）
export enum FuncListTypeEnum {
  None = 0,
  // OfficeManagement = 1,
  CityList = 2, // 区域管理
  CommunityList = 3, // 社区列表
  OfficeList = 4, // 办公室列表
  // TenancyManagement = 5,
  UserAppointmentList = 6, // 预约看房
  OrderList = 7, // 租赁订单
  // CustomerServiceManagement = 8,
  UserFeedBackList = 9, // 用户反馈
  // SystemManagement = 10,
  UserList = 11, // 后台账号管理
  CountryList = 12, // 国家管理
  // AuthList = 13 // 权限管理
}

// 菜单路径与枚举的映射
export const menuPathToEnum: Record<string, FuncListTypeEnum> = {
  "/regionManagement": FuncListTypeEnum.CityList,
  "/communityList": FuncListTypeEnum.CommunityList,
  "/officeList": FuncListTypeEnum.OfficeList,
  "/reservation": FuncListTypeEnum.UserAppointmentList,
  "/rentalOrder": FuncListTypeEnum.OrderList,
  "/customerServiceList": FuncListTypeEnum.UserFeedBackList,
  "/accountManagerList": FuncListTypeEnum.UserList,
  // "/authManagementList": FuncListTypeEnum.AuthList,
  "/countryManagementList": FuncListTypeEnum.CountryList,
};

export interface MenuChild {
  title: string;
  index: string;
  show: boolean;
  funcType?: FuncListTypeEnum;
  icon?: any;
  activeIcon?: any;
}

export interface MenuItem {
  title: string;
  icon?: any;
  activeIcon?: any;
  show: boolean;
  index?: string;
  funcType?: FuncListTypeEnum;
  child?: MenuChild[];
}

export default function useMenuRequest() {
  const isLoading = ref(false);
  const lastSentRequestType = ref<FuncListTypeEnum | null>(null);
  const debounceTimer = ref<number | null>(null);

  // 防抖处理
  const debounce = (func: Function, delay = 300) => {
    if (debounceTimer.value) clearTimeout(debounceTimer.value);
    debounceTimer.value = setTimeout(() => {
      func();
      debounceTimer.value = null;
    }, delay);
  };

  // 找到菜单项对应的功能类型
  const findFuncTypeByPath = (path: string, menuList: MenuItem[]): FuncListTypeEnum | null => {
    // 精确匹配
    if (menuPathToEnum[path]) {
      return menuPathToEnum[path];
    }

    // 前缀匹配
    const matchedPath = Object.keys(menuPathToEnum).find(p => path.startsWith(p));
    if (matchedPath) {
      return menuPathToEnum[matchedPath];
    }

    // 在菜单数据中查找
    for (const item of menuList) {
      if (item.child) {
        for (const childItem of item.child) {
          if (childItem.index === path && childItem.funcType) {
            return childItem.funcType;
          }
        }
      } else if (item.index === path && item.funcType) {
        return item.funcType;
      }
    }

    return null;
  };

  // 发送菜单请求的方法
  const sendMenuRequest = (funcType: FuncListTypeEnum) => {
    if (funcType === undefined || funcType === null) {
      return;
    }

    if (lastSentRequestType.value === funcType && isLoading.value) {
      return;
    }

    lastSentRequestType.value = funcType;
    isLoading.value = true;

    const funcTypeValue = Number(funcType);
    const adminStore = useAdminStore();
    const requestApi = new GetAdminList();
    requestApi.setQuery({ funcListType: funcTypeValue });
    requestApi.fetch().then(res => {
      if (res.data && Array.isArray(res.data)) {
        adminStore.setAdminList(res.data);
        console.log('设置 adminList 成功:', res.data); // 添加日志，确认数据设置
      }
      isLoading.value = false;
    }).catch(err => {
      isLoading.value = false;
    });
  };

  return {
    isLoading,
    findFuncTypeByPath,
    sendMenuRequest,
    debounce
  };
}